import request from '@/utils/request'
import widgetService from '@/api/widgetService'
import statisticsReportService from '@/api/statisticsReportService'

async function getMenu () {
  const res = await widgetService.getNavigatorsByAppNames(window.config.VUE_APP_NAME)
  const keys = Object.keys(res)
  for (let i = 0; i < keys.length; i++) {
    await addStatisticsReport(res[keys[i]])
  }
  return res
}

const userApi = {
  currentUser: 'auth/getCurrentUser',
  getUserUnit: 'orup/org/getUserUnit'
}

/**
 * 获取统计报表分组
 * @returns
 */
async function getStatisticsReports () {
  let result = []
  await statisticsReportService.listStatisticsReportsRootGroup().then((d) => {
    result = d
  })
  return result
}

/**
 * 如果存在统计报表模块，则查询报表所有分组，加入到菜单
 * @param {Array} list
 */
async function addStatisticsReport (list) {
  if (!list || !(list instanceof Array) || list.length === 0) { return list }
  const tempList = list.filter(item => { return item.componentType === 'TJBB' })
  if (tempList.length > 0) {
    const statisticsReports = await getStatisticsReports()
    list.forEach(item => {
      tempList.forEach(item1 => {
        if (item.id === item1.id) {
          item.children = statisticsReports
        }
      })
    })
  }
  return list
}

/**
 * 获取用户基本信息
 */
export function getUserInfo () {
  return request({
    url: userApi.currentUser,
    method: 'get'
  })
}

/**
 * 获取用户导航权限
 */
export function getNavigators () {
  return new Promise(resolve => {
    resolve(getMenu())
  })
}

export function getUserUnit (params) {
  return request({
    url: userApi.getUserUnit,
    method: 'get',
    params: params
  })
}

export function getUserOrg (params) {
  return request({
    url: userApi.getUserUnit,
    method: 'get',
    params: params
  })
}
